<?php
namespace App\Logic\SalesReportLT;

use App\Models\Basics\ExchangeRate;
use App\Models\MonthlyReportLT\Payment\PaymentCancelFee;
use App\Models\MonthlyReportLT\Payment\PaymentOrder;
use App\Models\MonthlyReportLT\Cost\LogisticsBasics;
use App\Models\MonthlyReportCommon\Cost\PriceBasics;
use App\Models\MonthlyReportLT\Payment\PaymentReFee;
use App\Models\MonthlyReportLT\Payment\PaymentSales;
use App\Models\MonthlyReportLT\Payment\PaymentThFee;
use App\Models\MonthlyReportLT\Payment\PaymentServiceFee;
use App\Models\Product\ProductSku;
use App\Models\Reimburse\ReimburseDetail;
use App\Models\SalesReportLT\PaymentDetail as TPaymentDetail;
use Illuminate\Support\Facades\DB;
class PaymentDetail
{
    public static function exePayment($date){
        try{
            $start = time();
            $start_memory = memory_get_usage();
            $purchasePrice = [];
            $shipmentPrice = [];
            $classify = [];
            $lines = PaymentOrder::query()
                ->where('report_date',$date)
                ->select('psku_id')
                ->distinct()
                ->get();
            $rateOdds = ExchangeRate::getRateOddsToRMB('JPY',strtotime($date));
            $i = 0;
            $num = 500;
            while(true){
                if($lines->isEmpty())break;
                $_lines = $lines->splice($i,$num);
                $paymentDetails = [];
                DB::beginTransaction();
                foreach ($_lines as $line){
                    $where = [
                        ['report_date',$date],
                        ['psku_id',$line->psku_id]
                    ];
                    $paymentDetail = [];
                    //品类
                    if(!array_key_exists($line->psku_id,$classify)){
                        $classify[$line->psku_id] =  ProductSku::getValueById($line->psku_id,'classify_id');
                    }
                    $paymentDetail['classify_id'] = $classify[$line->psku_id];
                    $paymentDetail['seller_id'] = 124;
                    $paymentDetail['rate_odds'] = $rateOdds;//汇率
                    //采购价格
                    $priceKey = $line->psku_id.'-'.$date;
                    if(!array_key_exists($priceKey,$purchasePrice)){
                        $purchasePrice[$priceKey] = PriceBasics::getPrice($line->psku_id,$date);
                    }
                    $purchasePriceRMB = $purchasePrice[$priceKey];
                    $paymentDetail['purchase_price_rmb'] = $purchasePriceRMB;
                    //物流运输价格
                    $lPriceKey = $line->psku_id.'-'.$date;
                    if(!array_key_exists($lPriceKey,$shipmentPrice)){
                        $shipmentPrice[$lPriceKey] = LogisticsBasics::getLogistics($line->psku_id,$date);//总运费成本RMB
                    }
                    $pSales = self::_getPaymentSales($date,$line->psku_id);
                    $paymentDetail['sales_volume'] = $pSales->quantity ?? 0;//销量
                    $paymentDetail['sales_amount'] = $pSales->sales ?? 0;//销售额
                    $paymentDetail['sales_amount_rmb'] = round($paymentDetail['sales_amount'] * $rateOdds,3);//销售额_RMB
                    $pRefee = self::_getPaymentReFee($date,$line->psku_id);
                    $paymentDetail['refund_num'] = $pRefee->quantity ?? 0;//退货量
                    $paymentDetail['refund_amount'] = $pRefee->sales ?? 0;//退货额
                    $paymentDetail['refund_amount_rmb'] = round($paymentDetail['refund_amount'] * $rateOdds,3);//退货额_RMB
                    $pThfee = self::_getPaymentThFee($date,$line->psku_id);
                    $paymentDetail['thfba'] = $pThfee->total ?? 0;//第三方FBA发货费
                    $paymentDetail['thfba_rmb'] = round($paymentDetail['thfba'] * $rateOdds,3);//第三方FBA发货费_RMB
                    $paymentDetail['t_purchase_price_rmb'] = round($paymentDetail['sales_volume'] * $paymentDetail['purchase_price_rmb'],3);//总采购成本RMB
                    $paymentDetail['t_shipment_price_rmb'] = $shipmentPrice[$lPriceKey];//总运费成本RMB
                    //额外费用
                    $cancelFee = self::_getPaymentCancelFee($date,$line->psku_id);
                    $paymentDetail['other_fee_rmb'] = round(($cancelFee->quantity ?? 0) * $paymentDetail['purchase_price_rmb']  + ($cancelFee->total ?? 0),3);
                    //服务费
                    $pServicefee = self::_getPaymentServiceFee($date,$line->psku_id);
                    $paymentDetail['system_use_pc_fee'] = $pServicefee->system_use_pc_fee ?? 0;
                    $paymentDetail['system_use_pc_fee_rmb'] = round($paymentDetail['system_use_pc_fee'] * $rateOdds,3);
                    $paymentDetail['system_use_sp_fee'] = $pServicefee->system_use_sp_fee ?? 0;
                    $paymentDetail['system_use_sp_fee_rmb'] = round($paymentDetail['system_use_sp_fee'] * $rateOdds,3);
                    $paymentDetail['system_use_c_fee'] = $pServicefee->system_use_c_fee ?? 0;
                    $paymentDetail['system_use_c_fee_rmb'] = round($paymentDetail['system_use_c_fee'] * $rateOdds,3);
                    $paymentDetail['super_membership_rewards_fee'] = $pServicefee->super_membership_rewards_fee ?? 0;
                    $paymentDetail['super_membership_rewards_fee_rmb'] = round($paymentDetail['super_membership_rewards_fee'] * $rateOdds,3);
                    $paymentDetail['super_membership_system_use_fee'] = $pServicefee->super_membership_system_use_fee ?? 0;
                    $paymentDetail['super_membership_system_use_fee_rmb'] = round($paymentDetail['super_membership_system_use_fee'] * $rateOdds,3);
                    $paymentDetail['super_membership_selling_fee'] = $pServicefee->super_membership_selling_fee ?? 0;
                    $paymentDetail['super_membership_selling_fee_rmb'] = round($paymentDetail['super_membership_selling_fee'] * $rateOdds,3);
                    $paymentDetail['super_membership_selling_re_fee'] = $pServicefee->super_membership_selling_re_fee ?? 0;
                    $paymentDetail['super_membership_selling_re_fee_rmb'] = round($paymentDetail['super_membership_selling_re_fee'] * $rateOdds,3);
                    $paymentDetail['integral_pc_fee'] = $pServicefee->integral_pc_fee ?? 0;
                    $paymentDetail['integral_pc_fee_rmb'] = round($paymentDetail['integral_pc_fee'] * $rateOdds,3);
                    $paymentDetail['integral_sp_fee'] = $pServicefee->integral_sp_fee ?? 0;
                    $paymentDetail['integral_sp_fee_rmb'] = round($paymentDetail['integral_sp_fee'] * $rateOdds,3);
                    $paymentDetail['rakuten_pay_use_fee'] = $pServicefee->rakuten_pay_use_fee ?? 0;
                    $paymentDetail['rakuten_pay_use_fee_rmb'] = round($paymentDetail['rakuten_pay_use_fee'] * $rateOdds,3);
                    $paymentDetail['rakuten_pay_visa_fee'] = $pServicefee->rakuten_pay_visa_fee ?? 0;
                    $paymentDetail['rakuten_pay_visa_fee_rmb'] = round($paymentDetail['rakuten_pay_visa_fee'] * $rateOdds,3);
                    $paymentDetail['service_fee'] = $pServicefee->service_fee ?? 0;
                    $paymentDetail['service_fee_rmb'] = round($paymentDetail['service_fee'] * $rateOdds,3);
                    $paymentDetail['spend'] = $pServicefee->spend ?? 0;
                    $paymentDetail['spend_rmb'] = round($paymentDetail['spend'] * $rateOdds,3);
                    $paymentDetail['total'] = $pServicefee->total ?? 0;
                    $paymentDetail['total_rmb'] = round($paymentDetail['total'] * $rateOdds,3);
                    //刷单费用
                    $paymentDetail['reimburse_rmb'] = self::_getReimburseRMB($date,$line->psku_id);//刷单费用RMB
                    $paymentDetail['reimburse_os_rmb'] = self::_getOperatingServiceRMB($date,$line->psku_id);//运营服务费RMB
                    $paymentDetail['reimburse_profit_rmb'] = self::_getReimburseProfitRMB($date,$line->psku_id);//刷单毛利扣减RMB
                    //毛利值RMB
                    $paymentDetail['profit_rmb'] = round($paymentDetail['sales_amount_rmb'] -
                        $paymentDetail['t_purchase_price_rmb'] -
                        $paymentDetail['t_shipment_price_rmb'] -
                        $paymentDetail['other_fee_rmb'] -
                        $paymentDetail['refund_amount_rmb'] -
                        $paymentDetail['thfba_rmb'] -
                        $paymentDetail['system_use_pc_fee_rmb'] -
                        $paymentDetail['system_use_sp_fee_rmb'] -
                        $paymentDetail['system_use_c_fee_rmb'] -
                        $paymentDetail['super_membership_rewards_fee_rmb'] -
                        $paymentDetail['super_membership_system_use_fee_rmb'] -
                        $paymentDetail['super_membership_selling_fee_rmb'] -
                        $paymentDetail['super_membership_selling_re_fee_rmb'] -
                        $paymentDetail['integral_pc_fee_rmb'] -
                        $paymentDetail['integral_sp_fee_rmb'] -
                        $paymentDetail['rakuten_pay_use_fee_rmb'] -
                        $paymentDetail['service_fee_rmb'] -
                        $paymentDetail['spend_rmb'] -
                        $paymentDetail['reimburse_rmb'] -
                        $paymentDetail['reimburse_os_rmb'] -
                        $paymentDetail['reimburse_profit_rmb'],3);
                    //销售收入
                    $paymentDetail['earning_rmb'] = round($paymentDetail['t_purchase_price_rmb'] +
                        $paymentDetail['t_shipment_price_rmb'] +
                        $paymentDetail['profit_rmb'],3);
                    $count = TPaymentDetail::query()->where($where)->count();
                    if($count > 0){
                        TPaymentDetail::query()->where($where)->update($paymentDetail);
                    }else{
                        $paymentDetail['report_date'] = $date;
                        $paymentDetail['psku_id'] = $line->psku_id;
                        $paymentDetails[] = $paymentDetail;
                    }
                }
                if(!empty($paymentDetails)){
                    DB::table('lt_sr_payment_detail')->insert($paymentDetails);
                }
                DB::commit();
            }
            $end = time();
            $end_memory = memory_get_usage();
            print_r(($end - $start).'--------'.(($end_memory - $start_memory)/1024/1024)) ;
        }catch (\Exception $e){
            report($e);
        }
    }

    //销量、销售额
    private static function _getPaymentSales($date,$pSkuId){
        return PaymentSales::where('report_date',$date)
            ->where('psku_id',$pSkuId)
            ->first();
    }

    //退货量、退货费
    private static function _getPaymentReFee($date,$pSkuId){
        return PaymentReFee::where('report_date',$date)
            ->where('psku_id',$pSkuId)
            ->first();
    }

    //第三方FBA发货费
    private static function _getPaymentThFee($date,$pSkuId){
        return PaymentThFee::where('report_date',$date)
            ->where('psku_id',$pSkuId)
            ->first();
    }

    //取消订单产生的费用
    private static function _getPaymentCancelFee($date,$pSkuId){
        return PaymentCancelFee::where('report_date',$date)
            ->where('psku_id',$pSkuId)
            ->first();
    }

    //服务费
    private static function _getPaymentServiceFee($date,$pSkuId){
        return PaymentServiceFee::where('report_date',$date)
            ->where('psku_id',$pSkuId)
            ->first();
    }

    //刷单RMB
    private static function _getReimburseRMB($date,$pSkuId){
        return 0;
//        return ReimburseDetail::where('fee_type',1)->where('paid_status',3)->where('report_date',$date)->where('country_id',$countryId)->where('seller_sku',$sellerSku)->sum('amount_rmb');
    }

    //运营服务费RMB
    private static function _getOperatingServiceRMB($date,$pSkuId){
        return 0;
//        return ReimburseDetail::where('fee_type','<>',1)->where('paid_status',3)->where('report_date',$date)->where('country_id',$countryId)->where('seller_sku',$sellerSku)->sum('amount_rmb');
    }

    //刷单毛利扣减RMB
    private static function _getReimburseProfitRMB($date,$pSkuId){
        return 0;
//        $rd = ReimburseDetail::select(DB::raw('sum(r_amount * r_rate_odds - purchase_price_rmb - shipment_price_rmb) as amount_rmb'))
//            ->where('fee_type',1)
//            ->where('paid_status',3)
//            ->where('report_date',$date)
//            ->where('country_id',$countryId)
//            ->where('seller_sku',$sellerSku)
//            ->value('amount_rmb');
//        return $rd ?: 0;
    }
}
